<template>
  <!-- 消息容器，根据消息角色和加载状态动态调整样式 -->
  <div 
    class="message-container"
    :class="[
      message.role === 'assistant' ? 'message-assistant' : 'message-user',
    ]"
  >

    <div class="message-avatar">
    </div>

    <!-- 消息内容，根据加载状态显示不同内容 -->
    <div class="message-content">
      <!-- 显示模式 -->
      <div class="message-text" v-if="!loading && !isEditing">
        <div 
        class="reasoning-toggle" 
        @click="isCollapsed = !isCollapsed"
        v-if="message.reasoning"
      >
        <div class="reasoning-preview">
          <span v-if="isCollapsed">显示思考过程</span>
          <span v-else>隐藏思考过程</span>
        </div>
      </div>
        <!-- 思考内容显示区域 -->
        <div v-if="!isCollapsed && message.reasoning" class="reasoning-container">
          <div class="markdown-body">
          <div v-html="renderMarkdown(cleanReasoning(message.reasoning))" class="reasoning-content-inner"></div>
          </div>
        </div>
        <!-- 分隔线 -->
        <div class="content-separator" v-if="message.content && message.reasoning"></div>

        <!-- 使用 v-html 渲染 Markdown 内容 -->
        <div class="markdown-body" v-html="renderMarkdown(cleanInference(message.content))" ref="markdownBody" @click="handleMarkdownClick"></div>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" />

      </div>

      <!-- 编辑模式 -->
      <div class="message-edit" v-if="isEditing">
        <el-input
          v-model="editContent"
          type="textarea"
          :rows="2"
          :autosize="{ minRows: 2, maxRows: 6 }"
          ref="editInputRef"
          @keydown.enter.exact.prevent="handleEditKeydown"
          @keydown.esc="cancelEdit"
        />
        <div class="edit-actions">
          <el-button size="small" @click="cancelEdit">取消</el-button>
          <el-button type="primary" size="small" @click="saveEdit">保存</el-button>
        </div>
      </div>

      <div class="message-loading" v-if="message.role === 'assistant' && message.isStreaming">
        <el-icon class="is-loading"><Loading /></el-icon>
        正在输出...
      </div>

      <!-- 消息底部区域：时间和操作按钮 -->
      <!-- <div class="message-footer">
        <span class="message-time">{{ formatTime(message.timestamp) }}</span>
      </div> -->
    </div>
  </div>
</template>

<script setup>
import { computed, ref, nextTick ,watch} from 'vue'
import { renderMarkdown } from '../utils/markdown'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete, RefreshRight, CopyDocument } from '@element-plus/icons-vue'
import { useChatStore } from '../stores/chat'
import aiAvatar from '@/assets/ai-avatar.png'
import { library } from '@fortawesome/fontawesome-svg-core';
import { faFileExcel, faFilePdf, faFileZipper, faFile } from '@fortawesome/free-solid-svg-icons';

// 新增折叠状态
const isCollapsed = ref(false); // 默认折叠
// // 新增：从 store 获取用户头像
// import { useUserStore } from '@/stores/user';
// const userStore = useUserStore();
// const userPhotoUrl = computed(() => userStore.userInfo.image);

library.add(
  faFileExcel, // Excel文件
  faFilePdf,   // PDF文件
  faFileZipper,// 压缩包
  faFile       // 默认文件图标
);



// 清理函数
const cleanReasoning = (content) => {
  // 去除 [reasoning] 和 [/reasoning] 标签，并去除最后一个换行符
  let cleanedContent = content.replace(/\[reasoning\]|\[\/reasoning\]/g, '').trim();
  // 去除最后一个换行符
  if (cleanedContent.endsWith('\n')) {
    cleanedContent = cleanedContent.slice(0, -1);
  }
  return cleanedContent;
};

const cleanInference = (content) => {
  // 去除 [inference] 和 [/inference] 标签，并去除最后一个换行符
  let cleanedContent = content.replace(/\[inference\]|\[\/inference\]/g, '').trim();
  // 去除最后一个换行符
  if (cleanedContent.endsWith('\n')) {
    cleanedContent = cleanedContent.slice(0, -1);
  }
  return cleanedContent;
};





// 定义组件属性
const props = defineProps({
  message: {
    type: Object,
    required: true
  }
});


// 监听 message 对象的变化
watch(
  () => props.message,
  (newMessage, oldMessage) => {
    console.log('消息对象变化：', {
      新内容: newMessage.content,
      新的思考内容: newMessage.reasoning,
      加载状态: newMessage.loading,
      旧内容: oldMessage.content,
      旧的思考内容: oldMessage.reasoning
    });
  },
  { deep: true } // 深度监听对象变化
);

const emit = defineEmits(['update', 'delete', 'regenerate'])

const markdownBody = ref(null)
const isEditing = ref(false)
const editContent = ref('')
const editInputRef = ref(null)


// 开始编辑
const startEdit = async () => {
  editContent.value = props.message.content
  isEditing.value = true
  // 等待 DOM 更新后聚焦输入框
  await nextTick()
  editInputRef.value?.input?.focus()
}

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false
  editContent.value = ''
}

// 保存编辑
const saveEdit = () => {
  if (!editContent.value.trim()) {
    ElMessage.warning('消息内容不能为空')
    return
  }
  emit('update', {
    ...props.message,
    content: editContent.value.trim()
  })
  isEditing.value = false
}

// 删除消息
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条消息吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    emit('delete', props.message)
  } catch {
    // 用户取消删除操作
  }
}

// 格式化时间函数
const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString()
}

// 在 computed 中添加 reasoningContent
const renderedReasoning = computed(() => {
  return renderMarkdown(
    props.message.reasoning || ''
  );
});

// 计算属性：渲染 Markdown 内容
const renderedContent = computed(() => {
  return renderMarkdown(
    props.message.content
  );
});

// 复制文本到剪贴板
const copyToClipboard = async (text) => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('代码已复制到剪贴板')
  } catch (err) {
    console.error('复制失败:', err)
    ElMessage.error('复制失败')
  }
}

// 处理代码块点击事件
const handleCodeBlockClick = (event) => {
  const preElement = event.target.closest('pre')
  if (preElement) {
    const codeElement = preElement.querySelector('code')
    if (codeElement) {
      copyToClipboard(codeElement.textContent)
    }
  }
}

// 处理编辑时的按键事件
const handleEditKeydown = (e) => {
  if (e.shiftKey) return // 如果按住 Shift，允许换行
  saveEdit() // 直接保存并发送
}

// 处理重新生成
const handleRegenerate = () => {
  console.log('重新生成')
  emit('regenerate', props.message)
}

// 复制全部内容
const handleCopyAll = async () => {
  try {
    await navigator.clipboard.writeText(props.message.content)
    ElMessage.success('内容已复制到剪贴板')
  } catch (err) {
    console.error('复制失败:', err)
    ElMessage.error('复制失败')
  }
}


const handleFileDownload = (url) => {
  window.open(url, '_blank');
};

// 修改点击事件处理函数
const handleMarkdownClick = (event) => {
  // 处理代码块复制
  const preElement = event.target.closest('pre');
  if (preElement) {
    handleCodeBlockClick(event);
    return;
  }

  // 处理文件卡片下载
  const fileCard = event.target.closest('.file-card');
  if (fileCard) {
    const url = fileCard.getAttribute('data-url');
    if (url) handleFileDownload(url);
  }
};

</script>



<style lang="scss" scoped>
// iOS Safari 特殊处理
@supports (-webkit-touch-callout: none) {
  .message-container {
    .message-content {
      .message-text {
        -webkit-overflow-scrolling: touch;
      }
    }
  }
}
// // 媒体查询补充
// @media (max-width: 900px) {
//   .chat-header {
//     padding: 0.5rem;
//   }
  
//   .message-container {
//     gap: 0rem !important;
//   }
// }

// @media (max-width: 375px) {
//   .file-card {
//     padding: 0.8rem !important;
//   }
// }

// @media (max-width: 414px) {
//   .markdown-body {
//     :deep() {
//       * {
//         white-space: pre-wrap;
//         word-wrap: break-word;
//         overflow-wrap: break-word;
//       }

//       code {
//         white-space: pre-wrap !important;
//         word-wrap: break-word !important;
//         font-size: 0.75rem !important;
//       }
//     }
//   }
// }


/* 移动端专属样式 */
@media (max-width: 768px) {
  .message-container {
    padding: 0.3rem;
    gap: 0.5rem;
    flex-direction: column;
    align-items: flex-start;
    max-height: 100% !important;

    .message-avatar {
      margin-bottom: 8px;
    }

    .message-content {
      max-width: 100% !important;
      .message-text {
      padding: 0.6rem 0.8rem !important;
      // padding-bottom: 0 !important;
      border-radius: 12px !important;
      word-break: break-word;
    }
    }
  }
  

  .markdown-body {
    :deep() {
      code {
        font-size: 0.8rem !important;
      }
      pre {
        font-size: 0.85rem !important;
        padding: 1rem 0.5rem !important;
      }
    }
  }

  .file-card {
    max-width: 100% !important;
    font-size: 0.85rem !important;
    .file-icon {
      width: 40px !important;
      height: 24px !important;
    }
  }

  .reasoning-toggle {
    font-size: 0.75rem;
    padding: 0.15rem 0.3rem;
  }

  .reasoning-container {
    padding: 0.5rem !important;
    font-size: 0.8rem !important;
  }
}


:root {
  --gray-bg-light: #f8f8fa;
  --gray-bg-hover: #e2e8f0;
  --border-color: #ced4da;
}
// 折叠按钮样式
.reasoning-toggle {
  cursor: pointer;
  padding: 0.25rem 0.5rem;
  background-color: var(--gray-bg-light);
  border-radius: 8px;
  margin-bottom: 0.25rem;
  transition: all 0.3s;
  font-size: 0.875rem;
  box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}

.reasoning-toggle:hover {
  background-color: var(--gray-bg-hover);
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

// 思考内容区域
.reasoning-container {
  background-color: var(--gray-bg);
  padding: 0.75rem;
  border-radius: 8px;
  margin-bottom: 0.5rem;
  font-size: 0.875rem;
  line-height: 1.4;
  box-shadow: 0 1px 2px rgba(0,0,0,0.08);
}

// 新增样式
.reasoning-content {
  margin-bottom: 1rem;
  padding: 1rem;
  background-color: var(--code-bg);
  border-radius: var(--border-radius);
  border: 1px solid var(--border-color);
  .reasoning-content-inner{
    white-space: pre-wrap; // 保留换行符
  }
}

// 分隔线
.content-separator {
  margin: 0.5rem 0;
  height: 1px;
  background-color: var(--border-color);
  opacity: 0.5;
}

.markdown-body2 {
  // border-radius: var(--border-radius) !important; // 添加圆角
  // border: 1px solid var(--border-color);
  padding: 1rem !important; // 添加内边距，使圆角效果更明显
  border-bottom: 1px dashed black;

  :deep() {
    // Markdown 内容样式
    h1, h2, h3, h4, h5, h6 {
      margin: 0.5rem 0;
      font-weight: 600;
      line-height: 1.25;
    }

    p {
      margin: 0.25rem 0;
    }

    code {
      font-family: var(--code-font-family);
      padding: 0.2em 0.4em;
      margin: 0;
      font-size: 85%;
      background-color: var(--code-bg);
      border-radius: 3px;
      color: var(--code-text);
    }

    pre {
      position: relative;
      padding: 2rem 1rem 1rem;
      overflow: auto;
      font-size: 85%;
      line-height: 1.45;
      background-color: var(--code-block-bg);
      border-radius: var(--border-radius);
      margin: 0.5rem 0;
      border: 1px solid var(--border-color);
      
      // 代码头部样式
      .code-header {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        padding: 0.3rem 1rem;
        background-color: var(--code-header-bg);
        border-bottom: 1px solid var(--border-color);
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-family: var(--code-font-family);
        
        .code-lang {
          font-size: 0.8rem;
          color: var(--text-color-secondary);
          text-transform: uppercase;
          letter-spacing: 0.5px;
        }
      }

      &::after {
        content: "点击复制";
        position: absolute;
        top: 0.3rem;
        right: 1rem;
        padding: 0.2rem 0.5rem;
        font-size: 0.75rem;
        color: var(--text-color-secondary);
        opacity: 0;
        transition: opacity 0.3s;
        font-family: system-ui, -apple-system, sans-serif;
      }

      &:hover::after {
        opacity: 0.8;
      }

      code {
        padding: 0;
        background-color: transparent;
        color: inherit;
        display: block;
        font-family: var(--code-font-family);
      }
    }

    blockquote {
      margin: 0.25rem 0;
      padding: 0 0.75rem;
      color: var(--text-color-secondary);
      border-left: 0.25rem solid var(--border-color);
    }

    ul, ol {
      margin: 0.25rem 0;
      padding-left: 1.5rem;
    }

    table {
      border-collapse: collapse;
      width: 100%;
      margin: 0.25rem 0;

      th, td {
        padding: 0.5rem;
        border: 1px solid var(--border-color);
      }

      th {
        background-color: var(--bg-color-secondary);
      }
    }

    img {
      max-width: 100%;
      max-height: 300px;
      object-fit: contain;
      margin: 0.5rem 0;
      border-radius: var(--border-radius);
      cursor: pointer;
      
      &:hover {
        opacity: 0.9;
      }
    }

    a {
      color: var(--primary-color);
      text-decoration: none;

      &:hover {
        text-decoration: underline;
      }
    }

    > *:last-child {
      margin-bottom: 0;
    }
  }
}



.file-card {
  display: flex;
  align-items: center;
  background: var(--code-block-bg);
  border-radius: var(--border-radius);
  padding: 1rem;
  margin: 0.5rem 0;
  cursor: pointer;
  transition: box-shadow 0.3s;

  &:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .file-icon {
    flex-shrink: 0;
    margin-right: 1rem;

    img {
      width: 48px;
      height: 48px;
      object-fit: contain;
    }
  }

  .file-info {
    flex: 1;
    
    .file-name {
      font-weight: 600;
      color: var(--text-color);
      max-width: 200px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .file-action {
      color: var(--primary-color);
      cursor: pointer;
      transition: color 0.2s;
      
      &:hover {
        color: var(--primary-color-light);
      }
    }
  }
}


.message-container {
  display: flex;
  // display: block;
  margin: 1rem 0;
  padding: 0.5rem;
  gap: 1rem;
  transition: all 0.3s ease;
  margin-bottom: 0.5rem;
  // white-space: pre-wrap;
  
  // 用户消息样式
  &.message-user {
    flex-direction: row-reverse;
    //翻转实现用户布局在右侧
    .message-content {
      align-items: flex-end;
    }
    // 用户消息的圆角样式
    .message-text {
      border-radius: 16px !important; // 强制覆盖默认值
      background-color: var(--bg-color); // 背景色
      word-break: break-word;
      padding: 12px 16px; // 可选: 调整内边距让圆角更明显
      // white-space: pre-wrap;
    }
  }


  // AI消息样式
  &.message-assistant {
  flex-direction: row; // 头像在左侧，内容在右侧

  .message-content {
    background-color: transparent !important;
    border: none;
    padding: 0;
    margin: 0;
    box-shadow: none;
  }

  .message-text {
    background-color: var(--bg-color);
    // padding: 0;
    padding: 12px 16px; // 可选: 调整内边距让圆角更明显
    border-radius: 16px !important;
    box-shadow: var(--box-shadow);
    // white-space: pre-wrap; // 自动换行
    // margin-left: 10px; // 内容与头像间距
    margin-top: 0.5rem; // 与思考内容区分间距
  }
  
  }
  

  .markdown-body {
    :deep() {
      // Markdown 内容样式
      h1, h2, h3, h4, h5, h6 {
        margin: 0.5rem 0;
        font-weight: 600;
        line-height: 1.25;
      }

      p {
        margin: 0.25rem 0;
      }

      code {
        font-family: var(--code-font-family);
        padding: 0.2em 0.4em;
        margin: 0;
        font-size: 85%;
        background-color: var(--code-bg);
        border-radius: 3px;
        color: var(--code-text);
      }

      pre {
        position: relative;
        padding: 2rem 1rem 1rem;
        overflow: auto;
        font-size: 85%;
        line-height: 1.45;
        background-color: var(--code-block-bg);
        border-radius: var(--border-radius);
        margin: 0.5rem 0;
        border: 1px solid var(--border-color);
        
        // 代码头部样式
        .code-header {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          padding: 0.3rem 1rem;
          background-color: var(--code-header-bg);
          border-bottom: 1px solid var(--border-color);
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-family: var(--code-font-family);
          
          .code-lang {
            font-size: 0.8rem;
            color: var(--text-color-secondary);
            text-transform: uppercase;
            letter-spacing: 0.5px;
          }
        }

        &::after {
          content: "点击复制";
          position: absolute;
          top: 0.3rem;
          right: 1rem;
          padding: 0.2rem 0.5rem;
          font-size: 0.75rem;
          color: var(--text-color-secondary);
          opacity: 0;
          transition: opacity 0.3s;
          font-family: system-ui, -apple-system, sans-serif;
        }

        &:hover::after {
          opacity: 0.8;
        }

        code {
          padding: 0;
          background-color: transparent;
          color: inherit;
          display: block;
          font-family: var(--code-font-family);
        }
      }

      blockquote {
        margin: 0.25rem 0;
        padding: 0 0.75rem;
        color: var(--text-color-secondary);
        border-left: 0.25rem solid var(--border-color);
      }

      ul, ol {
        margin: 0.25rem 0;
        padding-left: 1.5rem;
      }

      table {
        border-collapse: collapse;
        width: 100%;
        margin: 0.25rem 0;

        th, td {
          padding: 0.5rem;
          border: 1px solid var(--border-color);
        }

        th {
          background-color: var(--bg-color-secondary);
        }
      }

      img {
        max-width: 100%;
        max-height: 300px;
        object-fit: contain;
        margin: 0.5rem 0;
        border-radius: var(--border-radius);
        cursor: pointer;
        
        &:hover {
          opacity: 0.9;
        }
      }

      a {
        color: var(--primary-color);
        text-decoration: none;

        &:hover {
          text-decoration: underline;
        }
      }

/* 文件卡片整体布局 */
.file-card {
  display: flex;
  align-items: center;
  justify-content: space-between;
  max-width: 160px;
  padding: 8px 12px;
  margin: 8px 0;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.15);
  cursor: pointer;
  transition: background-color 0.3s;
}

.file-card:hover {
  background-color: #f5f5f5;
}

/* 左侧文件信息部分 */
.file-info {
  display: flex;
  flex-direction: column;
  margin-right: 12px;
}

.file-name {
      font-size: 14px;
      color: #333;
      font-weight: 500;
      margin-bottom: 4px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: calc(10ch); // 10个字符宽度（ch单位根据字体宽度计算）
    }

.file-size {
  font-size: 12px;
  color: #999;
}

/* 右侧图标部分 */
.file-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 32px;
  font-size: 40px;
  color: #4caf50;
}






.download-btn:hover {
  background-color: #218838;
}


      > *:last-child {
        margin-bottom: 0;
      }
    }
  }
}


.message-avatar {
  .el-avatar {
    width: 40px;
    height: 40px;
  }
}

.message-content {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  max-width: 80%;
}

.message-text {
  background-color: var(--bg-color);
  padding: 1rem;
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
  // white-space: pre-wrap;
}

.message-loading {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: var(--text-color-secondary);
  
  .el-icon {
    font-size: 1.2rem;
  }
}

.message-meta {
  font-size: 0.8rem;
  color: var(--text-color-secondary);
}

.message-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 0.5rem;
  font-size: 0.8rem;
  color: var(--text-color-secondary);
}

.message-time {
  margin-right: 0.5rem;
}

.message-actions {
  display: flex;
  gap: 0.25rem;
  opacity: 0.6;
  transition: opacity 0.2s ease;
  
  &:hover {
    opacity: 1;
  }
  
  .el-button {
    padding: 2px 4px;
    height: 20px;
    
    .el-icon {
      font-size: 14px;
    }
    
    &:hover {
      color: var(--primary-color);
      background-color: var(--bg-color-secondary);
    }
  }
}

.message-edit {
  background-color: var(--bg-color);
  padding: 0.75rem;
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);

  .el-input {
    margin-bottom: 0.5rem;
    
    :deep(.el-textarea__inner) {
      background-color: var(--bg-color-secondary);
      border-color: var(--border-color);
      resize: none; // 禁用手动调整大小
      
      &:focus {
        border-color: var(--primary-color);
      }
    }
  }

  .edit-actions {
    display: flex;
    justify-content: flex-end;
    gap: 0.5rem;
  }
}
</style>
